import React from "react";

interface CountDown{
    initialSeconds:number;
    buttonTextBefore:string;
    SendEmail:() => void;
}

const CountDown = (props:CountDown) => {
    const { initialSeconds, buttonTextBefore, SendEmail } = props;
    const [secondsLeft, setSecondsLeft] = React.useState(initialSeconds);
    const [isCountingDown, setIsCountingDown] = React.useState(false);
    const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

    React.useEffect(() => 
    {
        if(isCountingDown && secondsLeft > 0)
        {
            timerRef.current = setTimeout(() => {
                setSecondsLeft((prevSeconds: number) => prevSeconds - 1);
            }, 1000);
        }else if(secondsLeft === 0)
        {
            // 倒计时结束，并重置相关状态
            setIsCountingDown(false);
            setSecondsLeft(initialSeconds);
            if(timerRef.current)
            {
                clearTimeout(timerRef.current);
                timerRef.current = null;
            }
        }

        return () =>
        {
            if (timerRef.current) {
                clearTimeout(timerRef.current);
                timerRef.current = null;
            }
        };
    }, [isCountingDown, secondsLeft, initialSeconds]);

    const HandleButtonClick = () => 
    {
        // 发送验证码
        SendEmail()
        setIsCountingDown(true);
    };

    return (
        <React.UI.Button
            size={isCountingDown?'mini' :'small'}
            color="primary"
            disabled={isCountingDown}
            onClick={HandleButtonClick}
        >
            {isCountingDown? `${secondsLeft}秒` : buttonTextBefore}
        </React.UI.Button>
    );
};

export default CountDown;